<?php

/**
 * Request 工具类
 *
 * @author 煤老板 <meok23@sina.com>
 * @date   2017-06-01
 */

namespace fw\tool;

class Request
{
    /**
     * 获取客户端 IP
     *
     * @return string
     */
    public static function clientIp()
    {
        if ($ip = getenv("HTTP_CLIENT_IP")) {
        } else if ($ip = getenv("HTTP_X_FORWARDED_FOR")) {
        } else if (isset($_SERVER['REMOTE_ADDR'])) {
            $ip = $_SERVER['REMOTE_ADDR'];
        } else {
            $ip = '0';
        }
        return $ip;
    }

    /**
     * 判断 post 提交
     *
     * @return bool
     */
    public static function isPost()
    {
        if (!empty($_SERVER['REQUEST_METHOD']) && $_SERVER['REQUEST_METHOD'] === 'POST') {
            return true;
        }

        return false;
    }

    /**
     * 获取变量
     *
     * @param array $args   要获取的数组
     * @param null  $item   数组对应的键
     * @param null  $callback
     * @param null  $preset 预设值
     *
     * @return mixed|null
     */
    public static function input(&$args, $item = null, $callback = null, $preset = null)
    {
        if (is_null($item)) {
            return $args;
        }

        if (isset($args[$item])) {
            if (!empty($callback)) {
                $preset = call_user_func($callback, $args[$item]);
            } else {
                $preset = $args[$item];
            }
        } elseif (is_null($preset) && is_string($callback)) {
            $preset = callback_map_preset($callback);
        }

        return $preset;
    }

    public static function post($item = null, $callback = null, $preset = null)
    {
        return self::input($_POST, $item, $callback, $preset);
    }

    public static function get($item = null, $callback = null, $preset = null)
    {
        return self::input($_GET, $item, $callback, $preset);
    }

    public static function cookie($item = null, $callback = null, $preset = null)
    {
        return self::input($_COOKIE, $item, $callback, $preset);
    }
}

/**
 * 映射回调函数与预设值
 *
 * @param $callback
 *
 * @return mixed|null
 */
function callback_map_preset($callback)
{
    $map = [
        'trim' => '',
        'rtrim' => '',
        'ltrim' => '',
        'htmlspecialchars' => '',
    ];

    $preset = null;
    if (isset($map[$callback])) {
        $preset = $map[$callback];
    }

    return $preset;
}
